use core::panic;
use std::borrow::Borrow;

use macroquad::prelude::{error, Texture2D};
use reqwest::blocking;

use crate::api;

pub fn get_client() -> Result<blocking::Client, Box<dyn std::error::Error>> {
    return Ok(blocking::Client::builder()
        .proxy(reqwest::Proxy::all("socks5h://127.0.0.1:9050")?)
        .build()?);
}

pub fn request_posts(tag: &str) -> Result<api::GetPostsResponse, Box<dyn std::error::Error>> {
    let request_addr =
        String::from("https://mastodon.social/api/v1/timelines/tag/") + tag.trim_start_matches("#");
    let resp = get_client()?.get(request_addr).send();
    // panic!("{:?}", resp.expect("ff"));

    let result = resp
        .expect("sending failed")
        .json::<api::GetPostsResponse>()
        .expect("cannot deser");
    return Ok(result);
}

/// reason d'etre: do not return bytes to avoid depending on bytes.
pub fn request_texture(url: &str) -> Result<Texture2D, Box<dyn std::error::Error>> {
    println!("Loading avatar/texture: {}", url);
    if url.ends_with(".jpeg") || url.ends_with(".jpg") {
        error!("WARNING: jpeg is currently unsupported!");
        return Err("jpeg!")?;
    }
    let resp = get_client()?.get(url).send()?;
    // pritln!("{:#?}",Result<api::GetPostsResponse, Box<dyn std::error::Error>>  resp);
    let bytes = resp.bytes()?;
    let res: &[u8] = bytes.borrow();
    return Ok(Texture2D::from_file_with_format(res, None));
}
